package com.izhengyin.demo.concurrent.basic.thread.lockSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;

/**
 * @author zhengyin
 * Created on 2021/11/10
 */
public class AlternatePrint {
    public static void main(String[] args) {
        CountDownLatch downLatch = new CountDownLatch(2);
        List<Thread> threads = new ArrayList<>();
        String str = "1a2b3c4d5e";
        AtomicInteger counter = new AtomicInteger(0);
        threads.add(new Thread(() -> {
            while (true){
                LockSupport.park();
                int index = counter.getAndIncrement();
                if(index >= str.length()){
                    LockSupport.unpark(threads.get((index + 1)%threads.size()));
                    break;
                }
                System.out.println(Thread.currentThread().getName()+" : "+str.charAt(index));
                LockSupport.unpark(threads.get((index + 1)%threads.size()));
            }
            downLatch.countDown();
        }));
        threads.add(new Thread(() -> {
            while(true){
                LockSupport.park();
                int index = counter.getAndIncrement();
                if(index >= str.length()){
                    LockSupport.unpark(threads.get((index + 1)%threads.size()));
                    break;
                }
                System.out.println(Thread.currentThread().getName()+" : "+str.charAt(index));
                LockSupport.unpark(threads.get((index + 1)%threads.size()));
            }
            downLatch.countDown();
        }));
        threads.forEach(t -> t.start());
        LockSupport.unpark(threads.get(0));
        try {
            downLatch.await();
        }catch (InterruptedException e){

        }
    }

}
